﻿using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Pomelo.EntityFrameworkCore.MySql.Scaffolding.Internal;
using SmartParking.Entities;

namespace SmartParking.ORM.SmartParkingMySqlEntity;

public  class SmartParkingContext : DbContext
{
    public SmartParkingContext(DbContextOptions<SmartParkingContext> options)
        : base(options)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see https://go.microsoft.com/fwlink/?LinkId=723263.
        => optionsBuilder.UseMySql("server=localhost;database=smart_parking;uid=dbroot;pwd=123456", Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.40-mysql"));

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        ValueConverter iconValueConverter =
                new ValueConverter<string, string>(
                    // 页面→数据库的转换
                    PageToData => string.IsNullOrWhiteSpace(PageToData) ? null : ((int)PageToData.ToArray()[0]).ToString("x"),
                    // 数据库→页面的转换
                    DataToPage => DataToPage == null ? "" : ((char)int.Parse(DataToPage, NumberStyles.HexNumber)).ToString()
                    );
        modelBuilder.Entity<SysMenu>()
            .Property(m => m.MenuIcon)
            .HasConversion(iconValueConverter);

        base.OnModelCreating(modelBuilder);
    }


    public virtual DbSet<SysUser> SysUser { get; set; }
    public virtual DbSet<SysMenu> SysMenu { get; set; }
}
